var app = getApp();
const regeneratorRuntime = require('../../../utils/runtime.js');
let innerAudioContext = wx.createInnerAudioContext(); //创建音频实例 
const recordmanage = wx.getRecorderManager()
Page({
  
  onReady: function (e) {
   
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function () {
    let that = this;
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec();
  },


  data: {
    loading: false,
    plain: false,
    disabled: false,//按钮一旦点击提交 则不能操作

    isbreaking: true,
    imageurl:'',
    lyimage: app.myUlife.ulifeUrl +'/wx/voice_btn_icon_n.png',//默认图片 
    musicmc:'',//音频名称
    musicUrl:'',//音频地址
    formatedPlayTime: '00:00',
    playStatus: true, //未播放的图片
    curTimeVal: 0,
    slider_value: 0,//设置初始滑块位置为0
    
    pname: '',
    author: '',
    nj: '',
    bj: '',
    pcontent: '',
    yp: '',
    fm: '',
    bstate: 0,

    scimgs: [],//诗词内容临时图片
    scurls: [],//诗词内容图片

    musicarr:[],//诗词语音临时文件
    musicurls: [],//诗词语音文件
  },


  //开始录音
  ksly: function (e) {
    wx.showLoading({
      title: '录音中....',
    })
    const options = {
      duration: 600000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'aac',
      frameSize: 50
    }
    recordmanage.start(options)
    this.setData({
      isbreaking: true
    });
  },



  jsly: function (e) {
    wx.hideLoading()
    var that = this;
    recordmanage.stop(); //先停止录音
    recordmanage.onStop((res) => {  //监听录音停止的事件
      if (res.duration < 1000) {
        wx.showToast({
          title: '录音时间太短'
        })
        wx.hideLoading();
        return;
      } else {
        this.setData({
          isbreaking: false
        })
        var tempFilePath = res.tempFilePath; // 文件临时路径
        that.setData({
          musicUrl: tempFilePath
        })
        that.setData({
          curTimeVal: 0,
          formatedPlayTime: '00:00',
          playStatus: true, //图片展示为未播放  
        })
        innerAudioContext.seek(0);
        wx.hideLoading();
      }
    });
  },



//..............上传诗词封面图片start.................
  //上传图片
  uploadimage: function () {
    var that = this;
    wx.chooseImage({
      count: 1, //张数， 默认9
      sizeType: ['compressed'], //建议压缩图
      sourceType: ['album', 'camera'], // 来源是相册、相机
      success: function (res) {
        that.setData({
          imageurl: res.tempFilePaths[0]
        })
      }
    });
  },
  //删除图片
  delImage: function (e) {
    var that = this;
    that.setData({
      imageurl: ""
    })
  },
  //预览图片
  viewimage: function (e) {
    var imageurl = this.data.imageurl;
    wx.previewImage({
      current: imageurl, // 当前显示图片的http链接
      urls: [imageurl] // 需要预览的图片http链接列表
    })
  },
//..............上传诗词封面图片end.................




  //..............上传诗词内容图片start.................
  //上传图片
  uploadSCimages: function () {
    var that = this;
    wx.chooseImage({
      count: 4, //张数， 默认9
      sizeType: ['compressed'], //建议压缩图
      sourceType: ['album', 'camera'], // 来源是相册、相机
      success: function (res) {
        var scimgs = that.data.scimgs;
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          scimgs.push(res.tempFilePaths[i]);
        }
        that.setData({
          scimgs: scimgs
        })
      }
    });
  },
  //删除图片
  delSCImage: function (e) {
    var that = this;
    var scimgs = that.data.scimgs;
    var cuindex = e.target.dataset.index;
    scimgs.splice(cuindex, 1);
    that.setData({
      scimgs: scimgs
    })
  },
  //预览图片
  viewSCimage: function (e) {
    var cuindex = e.target.dataset.index;
    var that = this;
    var urls = that.data.scimgs;
    wx.previewImage({
      current: urls[cuindex], // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
 //..............上传诗词内容图片end.................



//..............诗词语音播放start.................
  //开始播放
  ksbf: function (e) {
    let that = this
    that.setData({ playStatus: false })
    var musicUrl = that.data.musicUrl; //音频url
    innerAudioContext.src = musicUrl;
    innerAudioContext.autoplay = true
    innerAudioContext.play();
    innerAudioContext.onPlay((res) => {
      innerAudioContext.onTimeUpdate((res) => {
        that.setData({
          duration: innerAudioContext.duration.toFixed(2) * 100,
          curTimeVal: innerAudioContext.currentTime.toFixed(2) * 100,
          formatedPlayTime: this.formatTime(innerAudioContext.currentTime)
        })
        var per = (innerAudioContext.currentTime / innerAudioContext.duration) * 100;
        that.setData({
          slider_value: per//设置slider滑块所在位置
        })
        if (innerAudioContext.duration.toFixed(2) - innerAudioContext.currentTime.toFixed(2) <= 0) {
          that.setStopState(that)
        }
        innerAudioContext.onEnded(() => {
          that.setStopState(that)
        })
      })
    })
  },
  setStopState: function (that) {
    that.setData({
      curTimeVal: 0,
      formatedPlayTime: '00:00',
      playStatus: true, //图片展示为未播放  
    })
    innerAudioContext.seek(0);
    innerAudioContext.stop(); 
  },

  //结束播放
  canel_handover() {
    // innerAudioContext.offPause(); //取消录音暂停
    innerAudioContext.pause(); //语音暂停
    this.setData({
      playStatus: true
    })
  },

  listenerSlider: function (e) {
    var per = e.detail.value; 
    var currentTime = (per / 100) * innerAudioContext.duration;
    innerAudioContext.seek(currentTime);//通过滑块控制音频进度
    this.formatTime(currentTime)
  }, 

  formatTime: (time) => {
    time = Math.floor(time);
    var m = Math.floor(time / 60).toString();
    m = m.length < 2 ? '0' + m : m;
    var s = (time - parseInt(m) * 60).toString();
    s = s.length < 2 ? '0' + s : s;
    return m + ':' + s;
  },

  removePlay: function () {
    this.setData({
      curTimeVal: 0,
      formatedPlayTime: '00:00',
      playStatus: true, //图片展示为未播放  
      musicUrl:''
    })
    innerAudioContext.stop(); 
    this.setData({
      isbreaking: true
    })
  },
//..............诗词语音播放end.................


  pnameinput(e) {
    this.setData({
      pname: e.detail.value
    })
  },

  authorinput(e) {
    this.setData({
      author: e.detail.value
    })
  },

  njinput(e) {
    this.setData({
      nj: e.detail.value
    })
  },


  bjinput(e) {
    this.setData({
      bj: e.detail.value
    })
  },

  pcontentinput(e) {
    var that=this;
    this.editorCtx.getContents({
      success: (res) => {
        that.setData({
          pcontent: res.html
        }); 
      },
      fail: res => { console.log("请求失败") }
    })
  },


  musicnametinput(e) {
    this.setData({
      musicmc: e.detail.value
    })
  },


  submitPoteryRead(e) {
    var that=this;
    var pname = this.data.pname;
    if (pname == '') {
      wx.showModal({
        title: '友情提示',
        content: '请填写诗词名称!',
        showCancel: !1,
      })
      return;
    }

    var author = this.data.author;
    if (author == '') {
      wx.showModal({
        title: '友情提示',
        content: '请填写诗词作者姓名!',
        showCancel: !1,
      })
      return;
    }

    var nj = this.data.nj;
    if (nj == '') {
      wx.showModal({
        title: '友情提示',
        content: '请填写接受任务的年级！',
        showCancel: !1,
      })
      return;
    }
    var bj = this.data.bj;
   

    var pcontent = this.data.pcontent;
    var scimgs = this.data.scimgs;
    if (pcontent == '' && scimgs.length<=0){
      wx.showModal({
        title: '友情提示',
        content: '请填写诗词内容或上传诗词内容图片！',
        showCancel: !1,
      })
      return;
    }

    var imageurl = this.data.imageurl;
    if (imageurl == '') {
      wx.showModal({
        title: '友情提示',
        content: '请上传诗词封面以方便展示！',
        showCancel: !1,
      })
      return;
    }

    wx.showModal({
      title: '提示',
      content: '是否发布任务,如果仅仅保存不需要发布，点击取消，否则点击确定',
      success(res) {
        wx.showLoading({
          title: '保存中',
        })
        that.setData({
          disabled: true,
          loading: true
        })
        if (res.confirm) {
          that.setData({
            bstate: "1"
          })
        } else if (res.cancel) {
          that.setData({
            bstate: "0"
          })
        }
        that.uploadImageFile();
      }
    })
  },

  uploadImageFile(){
    var that=this;
    var imageurl = this.data.imageurl;
    wx.uploadFile({
      url: app.myUlife.ulifeUrl + '/upload/uploadScdhFm.html', //上传服务器的地址
      filePath: imageurl, //临时路径
      name: 'file',
      header: {
        contentType: "multipart/form-data", //按需求增加
      },
      formData: null,
      success: function (res) {
        var img = JSON.parse(res.data);
        var urls = img.urls;
        that.setData({
          fm: urls
        })
      
        var scimgs = that.data.scimgs;
        var musicarr = that.data.musicarr;
        if (scimgs.length > 0){
          that.uploadScnrImageFile();
        } else if (musicarr.length > 0){
          that.uploadMusicFile();
        }else{
          that.savePoteryRead();
        }
      },
      fail: function (err) {
        wx.hideLoading();
        console.log(err.errMsg);//上传失败
      }
    });
  },


  uploadScnrImageFile() {
    var that = this;
    var scimgs = that.data.scimgs;
    var scurls = this.data.scurls;
    wx.uploadFile({
      url: app.myUlife.ulifeUrl + '/upload/uploadScdhFm.html', //上传服务器的地址
      filePath: scimgs[0], //临时路径
      name: 'file',
      header: {
        contentType: "multipart/form-data", //按需求增加
      },
      formData: null,
      success: function (res) {
        var img = JSON.parse(res.data);
        var urls = img.urls;
        scurls.push(urls);
        that.setData({
          scurls: scurls
        })
        that.data.scimgs.splice(0, 1);
        var musicarr = that.data.musicarr;
        if (that.data.scimgs.length > 0) {
          that.uploadScnrImageFile();
        } else if (musicarr.length > 0){
          that.uploadMusicFile();
        }else{
          that.savePoteryRead();
        }

      },
      fail: function (err) {
        wx.hideLoading();
        console.log(err.errMsg);//上传失败
      }
    });
  },



  uploadMusicFile() {
    var that = this;
    var musicarr = that.data.musicarr;
    var musicurls = that.data.musicurls;
    wx.uploadFile({
      url: app.myUlife.ulifeUrl + '/upload/uploadMusicurl.html', //上传服务器的地址
      filePath: musicarr[0].musicUrl, //临时路径
      name: 'file',
      header: {
        contentType: "multipart/form-data", //按需求增加
      },
      formData: null,
      success: function (res) {
        //上传失败
        var img = JSON.parse(res.data);
        var urls = img.urls;
        var urlitem={
          musicUrl: urls,
          musicmc: musicarr[0].musicmc
        }
        musicurls.push(urlitem);
        that.setData({
          musicurls: musicurls
        })
        that.data.musicarr.splice(0, 1);
        if (that.data.musicarr.length>0){
          that.uploadMusicFile();
        }else{
          that.savePoteryRead();
        }
      },
      fail: function (err) {
        wx.hideLoading();
        //上传失败
      }
    });
  },


  savePoteryRead() {
    var pname = this.data.pname;
    var author = this.data.author;
    var nj = this.data.nj;
    var bj = this.data.bj;
    var pcontent = this.data.pcontent;
    var fm = this.data.fm;
    var musicurls = this.data.musicurls;
    var scurls = this.data.scurls;
    var bstate = this.data.bstate;
    var publisher = wx.getStorageSync('usid');

    wx.request({
      url: app.myUlife.ulifeUrl + 'poetryread/savePoteryRead.html',
      data: {
        pname: pname,
        author: author,
        nj: nj,
        bj: bj,
        pcontent: pcontent,
        fm: fm,
        musicurls: JSON.stringify(musicurls),
        scurls: JSON.stringify(scurls),
        bstate: bstate,
        publisher: publisher
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.result) {
          wx.showModal({
            title: '成功',
            content: res.data.msg,
            showCancel: !1,
          });
          wx.reLaunch({
            url: '../../task/mytask/mytask'
          })
        } else {
          that.setData({
            disabled: false,
            loading: false
          })
          wx.showModal({
            title: '失败',
            content: res.data.msg,
            showCancel: !1,
          });
        }
      }
    })

  },







//..............诗词语音上传弹窗打开start.................
  //诗词语音上传打开
  scyyShow(e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.setData({
      musicmc: '',//音频名称
      musicUrl: '',//音频地址
    })
    this.openscyy(currentStatu);
  },


  //打开诗词语音弹窗
  openscyy(currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200, //动画时长  
      timingFunction: "linear", //线性  
      delay: 0 //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })
      //关闭  
      if (currentStatu == "close") {
        this.setData({
          showxdthplModalStatus: false
        });
      }
    }.bind(this), 200)
    // 显示  
    if (currentStatu == "open") {
      this.setData({
        showxdthplModalStatus: true
      });
    }
  },

  //确定诗词语音
  sureScyy() {
    var musicmc = this.data.musicmc;
    var musicUrl = this.data.musicUrl;
    if (musicmc == ""){
      wx.showModal({
        title: '失败',
        content: "请填写语音名称",
        showCancel: !1,
      });
      return;
    } 
    if (musicUrl == "") {
      wx.showModal({
        title: '失败',
        content: "请上传语音！",
        showCancel: !1,
      });
      return;
    }
    var musicarr = this.data.musicarr;
    var mu={
      musicmc: musicmc,
      musicUrl: musicUrl,
      playStatus:true,
    }
    musicarr.push(mu);
    this.setData({
      musicarr: musicarr
    });
    this.openscyy('close');
  },
//..............诗词语音上传弹窗打开end.................



//..............诗词语音播放start.................
  //开始播放
  ksbfsc: function (e) {
    let that = this
    var index = e.currentTarget.dataset.index;
    var musicarr = that.data.musicarr;
    musicarr[index].playStatus = false;
    that.setData({ musicarr: musicarr })
    var musicUrl = musicarr[index].musicUrl; //音频url
    innerAudioContext.src = musicUrl;
    innerAudioContext.autoplay = true
    innerAudioContext.play();
    innerAudioContext.onPlay((res) => {
      innerAudioContext.onTimeUpdate((res) => {
        if (innerAudioContext.duration.toFixed(2) - innerAudioContext.currentTime.toFixed(2) <= 0) {
          that.setStopSCState(index)
        }
        innerAudioContext.onEnded(() => {
          that.setStopSCState(index)
        })
      })
    })
  },
  setStopSCState: function (index) {
    let that = this
    var musicarr = that.data.musicarr;
    musicarr[index].playStatus = true;
    that.setData({ musicarr: musicarr })
    innerAudioContext.seek(0);
    innerAudioContext.stop();
  },
  //结束播放
  canel_playsc(e) {
    let that = this
    var index = e.currentTarget.dataset.index;
    innerAudioContext.pause(); //语音暂停
    var musicarr = that.data.musicarr;
    musicarr[index].playStatus = true;
    that.setData({ musicarr: musicarr })
  },
  delMusic(e){
    var index = e.currentTarget.dataset.index;
    var musicarr = this.data.musicarr;
    musicarr.splice(index, 1);
    this.setData({
      musicarr: musicarr
    })
  }
//..............诗词语音播放end.................

})